﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using Senparc.Weixin.MP.Entities;
using NHibernate.Criterion;
using System.Collections.Generic;
using ZLCMS.Business.Util;
using Senparc.Weixin.MP.Helpers;
using DotNet.Common.NHibernateUtil;
using Newtonsoft.Json;
using ZLCMS.Business.WeixinService.Data;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class EditProductCate : System.Web.UI.Page
    {
        protected FrameHelper _frameHelper;

        protected WxMaterial _materialDb;

        private string _uid;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            _frameHelper = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();
            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        private void Save()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                ITransaction tran = session.BeginTransaction();

                try
                {
                    if (string.IsNullOrEmpty(_uid))//新建
                    {
                        _materialDb = new WxMaterial();

                        _materialDb.Title = tb_name.Text;
                        _materialDb.MsgType = "vote";
                        _materialDb.CreateDate = DateTime.Now;
                        _materialDb.UpdateDate = DateTime.Now;
                        _materialDb.Status = "1";
                        _materialDb.OwnerAccount = _userAccount;

                        session.Save(_materialDb);

                        _voteDb = new WxVoteConfig();

                        _voteDb.Title = tb_name.Text;
                        _voteDb.Description = tb_desc.Text;
                        _voteDb.Content = txtContent.Value;

                        _voteDb.BeginDate = DateTime.Parse(tb_sdate.Text);
                        _voteDb.EndDate = DateTime.Parse(tb_edate.Text);
                        _voteDb.CreateDate = DateTime.Now;

                        List<WeixinVoteItemData> itemList = new List<WeixinVoteItemData>();

                        itemList.Add(new WeixinVoteItemData() { VoteKey = "A", VoteContent = tb_item_1.Text });
                        itemList.Add(new WeixinVoteItemData() { VoteKey = "B", VoteContent = tb_item_2.Text });
                        itemList.Add(new WeixinVoteItemData() { VoteKey = "C", VoteContent = tb_item_3.Text });
                        itemList.Add(new WeixinVoteItemData() { VoteKey = "D", VoteContent = tb_item_4.Text });

                        _voteDb.VoteData = JsonConvert.SerializeObject(itemList);

                        _voteDb.RuleDay = int.Parse(tb_day.Text);
                        _voteDb.RuleTimes = int.Parse(tb_times.Text);

                        _voteDb.VoteOpenUrl = fc_open.Value;

                        _voteDb.Status = "SETTING";
                        _voteDb.OwnerAccount = _userAccount;
                        
                        session.Save(_voteDb);
                    }
                    else//修改
                    {
                        _materialDb.Title = tb_name.Text;
                        _voteDb.Title = tb_name.Text;
                        _voteDb.Description = tb_desc.Text;
                        _voteDb.Content = txtContent.Value;

                        _voteDb.BeginDate = DateTime.Parse(tb_sdate.Text);
                        _voteDb.EndDate = DateTime.Parse(tb_edate.Text);

                        //活动开始后，不能修改
                        if (_voteDb.Status != "SETTING")
                        {
                            List<WeixinVoteItemData> itemList = new List<WeixinVoteItemData>();

                            itemList.Add(new WeixinVoteItemData() { VoteKey = "A", VoteContent = tb_item_1.Text });
                            itemList.Add(new WeixinVoteItemData() { VoteKey = "B", VoteContent = tb_item_2.Text });
                            itemList.Add(new WeixinVoteItemData() { VoteKey = "C", VoteContent = tb_item_3.Text });
                            itemList.Add(new WeixinVoteItemData() { VoteKey = "D", VoteContent = tb_item_4.Text });

                            _voteDb.VoteData = JsonConvert.SerializeObject(itemList);
                        }

                        _voteDb.RuleDay = int.Parse(tb_day.Text);
                        _voteDb.RuleTimes = int.Parse(tb_times.Text);

                        _voteDb.VoteOpenUrl = fc_open.Value;

                        session.Update(_materialDb);
                        session.Update(_voteDb);
                    }

                    session.Flush();
                    tran.Commit();
                }
                catch (System.Exception ex)
                {
                    tran.Rollback();

                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _frameHelper.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                navTabId = _frameHelper.NavTabId
            });
        }
        
        protected void InitializeGlobalValue()
        {
            if (!IsPostBack)
            {
                ViewState["uid"] = Request["uid"];
            }
            _uid = (string)ViewState["uid"];

            if (!string.IsNullOrEmpty(_uid))
            {
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        _voteDb = session.CreateCriteria<WxVoteConfig>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxVoteConfig>(); 

                        if (_voteDb == null)
                        {
                            throw new Exception("找不到对应信息.");
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                        return;
                    }
                }
            }
        }

        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(_uid))
                {
                    tb_name.Text = _voteDb.Title;
                    tb_desc.Text = _voteDb.Description;
                    txtContent.Value = _voteDb.Content;

                    tb_sdate.Text = _voteDb.BeginDate.ToString("yyyy-MM-dd");
                    tb_edate.Text = _voteDb.EndDate.ToString("yyyy-MM-dd");

                    List<WeixinVoteItemData> itemList = JsonConvert.DeserializeObject<List<WeixinVoteItemData>>(_voteDb.VoteData);

                    tb_item_1.Text = itemList[0].VoteContent;
                    tb_item_2.Text = itemList[1].VoteContent;
                    tb_item_3.Text = itemList[2].VoteContent;
                    tb_item_4.Text = itemList[3].VoteContent;

                    if (_voteDb.Status != "SETTING")
                    {
                        tb_item_1.Enabled = false;
                        tb_item_2.Enabled = false;
                        tb_item_3.Enabled = false;
                        tb_item_4.Enabled = false;
                    }

                    tb_day.Text = _voteDb.RuleDay.ToString();
                    tb_times.Text = _voteDb.RuleTimes.ToString();
                    
                    fc_open.Value = _voteDb.VoteOpenUrl;
                }
                else
                {
                    tb_name.Text = "微信投票";
                    tb_desc.Text = "亲，请点击进入微信投票页面，感谢你的参与!";
                    txtContent.Value = "亲，请点击进入微信投票页面，感谢你的参与!";

                    tb_sdate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    tb_edate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    
                    tb_day.Text = "1";
                    tb_times.Text = "1";
                }
            }
        }
    }
}
